package com.lolaage.tsr.dals.ds;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.lolaage.tsr.dals.util.ContextUtil;

//import cn.org.farseer.dals.util.ContextUtil;

/**
 * @author 邓鹏
 * @Project Farseer-farseer-dals
 * @Date 2012-12-31
 * @ReMarks 
 */
public class RouteDBFactory {
	Logger log = Logger.getLogger(RouteDBFactory.class);
	private static RouteDBFactory inst;
	private RouteDBFactory() {
	}
	
	public static RouteDBFactory getInstance() {
		if (inst == null) inst = new RouteDBFactory();
		return inst;
	}
	
	public Long getId(String tableName) {
		//初始化ID为0,再取一次
		Long id = getAutoIncrementId(tableName);
		if (id == 0)
			id = getAutoIncrementId(tableName);
		if (log.isDebugEnabled())
			log.debug("get id " + id + " for " + tableName);
		return id;
	}
	public Long getIdUseJdbc(String tableName) {
		//初始化ID为0,再取一次
		Long id = getAutoIncrementIdUseJdbc(tableName);
		if (id == 0)
			id = getAutoIncrementIdUseJdbc(tableName);
		if (log.isDebugEnabled())
			log.debug("get id " + id + " for " + tableName);
		return id;
	}
	
	private Long getAutoIncrementIdUseJdbc(String tableName) {
		Long id = null;
		try {
			DataSource ds = new LolaageDataSource(ContextUtil.getInitConfig("routedb.url")
					, ContextUtil.getInitConfig("routedb.username"), ContextUtil.getInitConfig("routedb.password"));
			Connection conn = ds.getConnection();
			if (!conn.isClosed()) {
				Statement statement = conn.createStatement();
				statement.execute("INSERT INTO `routedb` (name) VALUES('"+tableName+"') ON DUPLICATE KEY UPDATE `id` = LAST_INSERT_ID(`id`+1)");
				ResultSet rs = statement.executeQuery("SELECT LAST_INSERT_ID()");
				while (rs.next()) {
					id = rs.getLong(1);
				}
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (log.isDebugEnabled())
				log.debug("error get id with message [" + e.getMessage() + "]");
		}
		return id;
	}
	private Long getAutoIncrementId(String tableName) {
		Long id = null;
		try {
			DataSource ds = (DataSource) ContextUtil.getBean("routedbDataSource");
			Connection conn = ds.getConnection();
			if (!conn.isClosed()) {
				Statement statement = conn.createStatement();
				/*statement.execute("INSERT INTO `routedb` (name) VALUES('"+tableName+"') ON DUPLICATE KEY UPDATE `id` = LAST_INSERT_ID(`id`+1)");
				ResultSet rs = statement.executeQuery("SELECT LAST_INSERT_ID()");*/
				ResultSet rs = statement.executeQuery("CALL getId('"+tableName+"')");
				while (rs.next()) {
					id = rs.getLong(1);
				}
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (log.isDebugEnabled())
				log.debug("error get id with message [" + e.getMessage() + "]");
		}
		return id;
	}
}
